/**
 * 
 */
package com.taobao.wolfwolf.taobao;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;

import com.taobao.api.ApiException;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.taobao.api.response.TradesSoldGetResponse;

/**
 * @author qinanhg 创建日期: 2012-3-10 上午1:19:11
 */
public class Trade extends Taobao {
	private List<Object[]> tradeCollect;
	private String status;
	
	public Trade(String status) {
		this.status = status;
		getTrades();
	}
	
	/**
	 * 获取单个订单信息
	 * @param tid
	 */
	@SuppressWarnings("unchecked")
	private void getTrade(long tid) {
		List<String[]> orders_list = null;
		// 多个 tid 集合
		List<Long> ordersTid = new ArrayList<Long>();
		
		TradeFullinfoGetRequest req=new TradeFullinfoGetRequest();
		req.setFields("seller_nick,buyer_nick,title,buyer_message,payment,seller_memo,type,created,sid,tid,buyer_rate,status,payment,pay_time,end_time,modified,consign_time,received_payment,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type");
		req.setTid(tid);
		
		try {
			TradeFullinfoGetResponse response = client.execute(req,	TaoBaoUtil.SESSIONKEY);

			Document document = DocumentHelper.parseText(response.getBody());

			List<DefaultElement> list = document.selectNodes("//trade_fullinfo_get_response/trade");

			for (DefaultElement trade_element : list) {
				Object[] trade = new Object[9];
				
				String buyer_nick = trade_element.elementText("buyer_nick");
				String buyer_message = trade_element.elementText("buyer_message");
				String seller_memo = trade_element.elementText("seller_memo");
				String total_fee = trade_element.elementText("payment");
				String pay_time = trade_element.elementText("pay_time");
				
				trade[0] = tid;
				trade[1] = false;
				trade[2] = ordersTid;
				trade[4] = buyer_nick;
				if(buyer_message != null) 
					trade[5] = buyer_message;
				else 
					trade[5] = "";
				if(seller_memo != null) 
					trade[6] = seller_memo;
				else
					trade[6] = "";
				trade[7] = total_fee;
				trade[8] = pay_time;
				
				int atid = isExistTid(buyer_nick);
				
				// 如果一个买家分拍了2单(就是2个订单号),就先得到之前拍的订单号,然后把第二单的商品添加到第一单中
				if(atid != -1) {
					trade = updateTrades(tradeCollect.get(atid), tid, (String) trade[5], (String) trade[6]);
					orders_list = (List<String[]>) trade[3];
				} else {
					orders_list = new ArrayList<String[]>();
				}
				
				Element orders_element = trade_element.element("orders");
				
				
				for(DefaultElement order_element : (List<DefaultElement>) orders_element.elements("order")) {
					String[] orders = new String[6];
					
					String title = order_element.elementText("title");
					String num_iid = order_element.elementText("num_iid");
					String sku_properties_name = order_element.elementText("sku_properties_name");
					String sku_id = order_element.elementText("sku_id");
					String num = order_element.elementText("num");
					String pic_path = order_element.elementText("pic_path");
					
					orders[0] = title;
					orders[1] = num_iid;
					orders[2] = sku_properties_name;
					orders[3] = sku_id;
					orders[4] = num;
					orders[5] = pic_path;
					
					orders_list.add(orders);
				}
				trade[3] = orders_list;
				if(atid != -1)
					tradeCollect.set(atid, trade);
				else
					tradeCollect.add(trade);
				
			}

		} catch (ApiException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取多个订单
	 */
	@SuppressWarnings("unchecked")
	private void getTrades() {
		tradeCollect = new ArrayList<Object[]>();
		
		TradesSoldGetRequest req = new TradesSoldGetRequest();
		
		req.setFields("tid");
		req.setStatus(status);
		// TODO 如果订单超过40个就会有问题
		req.setPageSize(100l);
		try {
			TradesSoldGetResponse response = client.execute(req,
					TaoBaoUtil.SESSIONKEY);

			Document document = DocumentHelper.parseText(response.getBody());

			List<DefaultElement> list = document.selectNodes("//trades_sold_get_response/trades/trade");

			for (DefaultElement trades_element : list) {
				long tid = Long.valueOf(trades_element.elementText("tid"));
				getTrade(tid);
			}
			
		} catch (ApiException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 合并多个交易为一个交易,交易里的订单在此合并
	 * @param trades
	 * @param tid
	 * @return
	 */
	public Object[] updateTrades(Object[] trades, long tid, String buyer_message, String seller_memo) {
		if(trades != null) {
			trades[1] = true;
			
			@SuppressWarnings("unchecked")
			List<Long> ordersTid = (List<Long>) trades[2];
			ordersTid.add(tid);
			
			trades[2] = ordersTid;
			trades[5] = trades[5] + buyer_message;
			trades[6] = trades[6] + seller_memo;
			
			return trades;
		}
		return null;
	}
	
	/**
	 * 查找 tradesCollect 中是否有相同的买家
	 * @param buyer_nick
	 * @return
	 */
	public int isExistTid(String buyer_nick) {
		int i = 0;
		for(Object[] o : tradeCollect) {
			if(o[4].equals(buyer_nick))
				return i;
			i++;
		}
		return -1;
	}

	/**
	 * <p>
	 * <b>Trades</b><br>
	 * [tid, 是否是多个订单, 多个订单的tid(如果只有一个订单,则这个字段就空着), 订单列表, 买家id, 买家留言, 卖家留言,付款时间]
	 * </p>
	 * <p>
	 * <b>orders</b><br>
	 * [名称, iid, 类别名称, 类别id, 购买数量,商品图片地址]
	 * </p>
	 * @return
	 */
	public List<Object[]> getTradesCollect() {
		return tradeCollect;
	}

	public void setTradesCollect(List<Object[]> tradesCollect) {
		this.tradeCollect = tradesCollect;
	}

	public static void main(String[] args) {
	}

}
